//
//  NSString+SJAdd.m
//  SJCommonToolkit
//
//  Created by Saxon on 2018/4/11.
//  Copyright © 2018年 remotevillage. All rights reserved.
//

#import "NSString+SJAdd.h"
#import <CommonCrypto/CommonDigest.h>

@implementation NSString (SJAdd)
- (NSString*) md5{
    if (![self hasValue]) return self;
    NSData *data = [self dataUsingEncoding:NSUTF8StringEncoding];
    unsigned char result[CC_MD5_DIGEST_LENGTH];
    CC_MD5(data.bytes, (CC_LONG)data.length, result);
    return [NSString stringWithFormat:
            @"%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x",
            result[0],  result[1],  result[2],  result[3],
            result[4],  result[5],  result[6],  result[7],
            result[8],  result[9],  result[10], result[11],
            result[12], result[13], result[14], result[15]
            ];
}
- (BOOL) hasValue {
    if (![self isKindOfClass:[NSString class]]) {
        return NO;
    }
    if (self && ![self isEqualToString:@""]) {
        return YES;
    }
    return NO;
}
- (NSString *) paramValueOfUrl:(NSString *) param{
    
    NSError *error;
    NSString *regTags=[[NSString alloc] initWithFormat:@"(^|&|\\?)+%@=+([^&]*)(&|$)",param];
    NSRegularExpression *regex = [NSRegularExpression regularExpressionWithPattern:regTags
                                                                           options:NSRegularExpressionCaseInsensitive
                                                                             error:&error];
    
    // 执行匹配的过程
    NSArray *matches = [regex matchesInString:self
                                      options:0
                                        range:NSMakeRange(0, [self length])];
    for (NSTextCheckingResult *match in matches) {
        NSString *tagValue = [self substringWithRange:[match rangeAtIndex:2]];  // 分组2所对应的串
        return tagValue;
    }
    return nil;
}
@end
